/*
 * Buffer.cpp
 *
 *  Created on: 2012-9-3
 *      Author: yangentao@gmail.com
 */

#include "TextBuffer.h"

TextVector::TextVector() :
		SplitVec<char>(8) { //TODO 8->512
}
AutoActionGroup::AutoActionGroup(TextBuffer* textBuffer_) {
	textBuffer = textBuffer_;
	textBuffer->actionMgr.beginGroup();
}
AutoActionGroup::~AutoActionGroup() {
	textBuffer->actionMgr.endGroup();
}

TextBuffer::TextBuffer() {
	actionMgr.setTextReplacable(this);
}
TextBuffer::~TextBuffer() {

}

void TextBuffer::addTextListener(TextListener* textListener) {
	textListeners.append(textListener);
}

void TextBuffer::addPosListener(PosListener* posListener) {
	posListeners.append(posListener);
}

String TextBuffer::getCharRange(int position, int length) const {
	String s(length);
	text.getRange(s.getBufferWrite(), position, length);
	s.setLength(length);
	return s;
}

String TextBuffer::textReplace(int from, int len_, const String& newText) {
	String oldText = getCharRange(from, len_);

	for (int i = 0; i < textListeners.size(); ++i) {
		textListeners[i]->onTextReplacing(from, oldText, newText);
	}
	int delta = newText.length() - len_;
	int to = from + len_;
	for (int i = 0; i < posListeners.size(); ++i) {
		posListeners[i]->onPosChanging(to, text.length(), delta);
		posListeners[i]->onPosRemoving(from, to);

	}

	text.replace(from, len_, newText.getBufferRead(), newText.length());
	lineMgr.onTextReplaced(from, len_, newText);
	posMgr.onTextReplaced(from, len_, newText.length());
	for (int i = 0; i < textListeners.size(); ++i) {
		textListeners[i]->onTextReplaced(from, oldText, newText);
	}
	for (int i = 0; i < posListeners.size(); ++i) {
		posListeners[i]->onPosChanged(to, text.length(), delta);
		posListeners[i]->onPosRemoved(from, to);

	}

	return oldText;
}

